<?php

namespace App\Admin\Controllers;

use App\Models\AdminApiMenusModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ApiMenusController extends Controller
{
    public function list()
    {
        $page_size = $this->request->post('size', 10);
        $page = $this->request->post('page', 1);
        $offset = ($page - 1) * $page_size;
        $offset = $offset > 0 ? $offset : 0;

        $api_menus_parents = AdminApiMenusModel::query()->where('pid', 0)->limit($page_size)->offset($offset)->get()->toArray();
        $pids = array_column($api_menus_parents, 'id');
        $api_menus_sons = AdminApiMenusModel::query()->whereIn('pid', $pids)->get()->toArray();

        $total = AdminApiMenusModel::query()->where('pid', 0)->count();

        $api_menus = array_merge($api_menus_parents, $api_menus_sons);
        return $this->success(['list' => array_values(listToTree($api_menus)), 'total' => $total]);
    }

    public function getAllList()
    {
        $has_child = $this->request->post('has_child', 0);

        $api_menus = AdminApiMenusModel::query()->get()->toArray();

        if ($has_child) {
            $api_menus = array_values(listToTree($api_menus));
        }

        return $this->success($api_menus);
    }

    public function addOrEditMenu()
    {
        $params = $this->request->post();
        $validator = Validator::make($params, [
            'name' => ['required', 'max:255'],
            'controller' => ['required', 'max:255'],
            'action' => ['required', 'max:255'],
            'is_check' => ['boolean'],
        ]);

        if ($validator->fails()) {
            return $this->fail(CODE_ERR_BAD_REQUEST, $validator->errors()->first());
        }

        $data = [
            'name' => $params['name'],
            'controller' => trim($params['controller']),
            'action' => trim($params['action']),
            'is_check' => isset($params['is_check']) ? (int)$params['is_check'] : YES,
            'pid' => $params['pid'] ?: 0
        ];

        if (empty($params['id'])) {
            $re = AdminApiMenusModel::query()->insert($data);
        } else {
            $re = AdminApiMenusModel::query()->where('id', $params['id'])->update($data);
        }

        if (!$re) {
            return $this->fail(CODE_ERR_SYSTEM, '操作失败');
        }

        return $this->success();
    }

    public function delMenu()
    {
        $menu_id = $this->request->post('menu_id', 0);

        if ($menu_id == 0) {
            return $this->fail(CODE_ERR_PARAM,'菜单不存在');
        }

        $re = AdminApiMenusModel::query()->where('id', $menu_id)->delete();

        if (!$re) {
            $this->fail(CODE_ERR_SYSTEM, '删除失败');
        }

        return $this->success();
    }
}
